local require = require
local utils   = require("modules.business_common.business_utils")
local config  = require("modules.business_common.business_config")
local http    = require("modules.business_common.utils.business_http")
local uu = require("modules.commhm.utils");
local log        = require("modules.commhm.log")
local ngx = ngx
local curr = os.time

local table = table
local pairs = pairs
local ipairs = ipairs
local tostring = tostring
local tonumber = tonumber
local loadstring = table.loadstring

local FOO = {
    _VERSION = '0.0.1'
}

local http_request = function(uin, request)
    if not (request and request.cmd) then
        return nil
    end
    local md5_params = {}
    request.uin  = uin
    request.ts = curr()
    for k, v in pairs(request) do
        if k ~= "cmd" then
            table.insert(md5_params, k.."="..v)
        end
    end
    table.sort(md5_params, function(lh, rh) if lh < rh then return true end end)
    local md5_str = table.concat(md5_params, "&")
    local private_key = "Sf5ym2r8NjNdj6Sb"
    request.sign = ngx.md5(md5_str..private_key)
    if request.ext then
        request.ext = ngx.escape_uri(request.ext)
    end
    local server = config.get_rank_url()

    local response = uu.json2table(http.Get(server, request) or 'nil')
    if response and tonumber(response.code) == 0 then
        return true, response.data or {}
    end

    http.Log(utils.hm.to_str({server = server, request = request, response = response}))
    return false
end


-- ! @ 设置排行榜
FOO.set_rank = function (uin, rank_id, score, frame, incr, ext)
    uin = uin or ngx.ctx.m_params.uin
    return http_request(uin, {
        cmd = 'set',
        rankId = rank_id,
        score = score,
        frame = frame,
        ext = ext,
        incr = incr,
    })
end


FOO.get_rank = function (uin, rank_id, limit, sort, uins, frame) 
    uin = uin or ngx.ctx.m_params.uin
    return http_request(uin, {
        cmd = 'get',
        rankId = rank_id,
        limit = limit,
        sort = sort,
        uins = uins,
        frame = frame,
    })
end

return FOO